<template>
    <div class="container">
        <Navbar title="我的订单" left-text="返回" left-arrow @click-left="goBack" fixed placeholder></Navbar>

        <van-tabs sticky @click-tab="onClickTab" offset-top="2.875rem" v-model:active="active">
            <van-tab :title="item.title" v-for="(item, index) in tags" :key="item.name">
                <div class="items" v-for="item in Orders" :key="item.id" v-if="show">

                    <van-cell icon="shop-o" class="items_t">
                        <template #title>
                            <div>
                                订单号: {{ item.code }}
                            </div>
                        </template>
                        <template #label>
                            <div>
                                <p>下单时间：{{ item.createtime_text }}</p>

                            </div>
                        </template>
                        <template #right-icon>
                            <div style="display: flex;flex-direction: column;text-align: right;">
                                <div class="desc">
                                    <van-button v-if="item.status != 5" type="primary" size="mini"
                                        :to="{ path: '/user/order/details', query: { orderid: item.id } }">订单详情
                                    </van-button>
                                </div>
                                <div class="tags_r">
                                    <van-tag size="medium" type="warning" v-if="item.status == 1">未发货</van-tag>
                                    <van-tag size="medium" color="#7232dd" v-if="item.status == 2">已发货</van-tag>
                                    <van-tag size="medium" type="success" v-if="item.status == 3 || item.status == 4">
                                        已收货
                                    </van-tag>
                                </div>
                            </div>
                        </template>
                    </van-cell>

                    <van-card v-for="(ele, index) in item.order_product" :key="ele.id" :thumb="ele.product.cover_cdn">
                        <template #title>
                            <p>商品名称: {{ ele.product.name }}</p>
                        </template>
                        <!-- <template #desc>
                            <p>下单时间：{{ item.createtime_text }}</p>
                        </template> -->
                        <template #desc>
                            <div class="flex" style="justify-content: space-between;">
                                <div style="display: flex;">单价：<h3>￥ {{ ele.price }}</h3>
                                </div>
                                <span>x {{ ele.nums }}</span>
                            </div>
                            <div class="flex">
                                <div style="display: flex;">总价：<h3>￥ {{ ele.total }}</h3>
                                </div>
                            </div>
                        </template>
                        <!-- <template #footer>
                            <van-button size="mini" type="danger">再来一单</van-button>
                        </template> -->
                    </van-card>

                    <van-collapse v-model="activeName" accordion>
                        <van-collapse-item :name="item.id">
                            <template #title>
                                <van-button size="mini"
                                    color="linear-gradient(25deg, #7c0bff, #b416c7, #d32a92, #e63e5c)">再来一单</van-button>
                            </template>

                            <van-button type="primary" size="mini" v-if="item.status >= 1 && item.status <= 4"
                                @click="Aftersales">申请售后
                            </van-button>
                            <van-button type="primary" size="mini"
                                :to="{ path: '/user/order/express', query: { orderid: item.id } }"
                                v-if="(item.status >= 2 && item.status <= 4) || item.status < 0">查看物流</van-button>
                            <van-button size="mini" type="danger" v-if="item.status == 5" @click="delOrder(item.id)">
                                取消订单
                            </van-button>
                            <van-button size="mini" type="danger" v-if="item.status >= 3 && item.status != 5"
                                @click="deleteOrder(item.id)">
                                删除订单
                            </van-button>
                            <van-button size="mini" v-if="item.status == 5" @click="goToCash(item.id)">立即支付</van-button>
                            <van-button size="mini" v-if="item.status == 2" @click="showPopup(item.id)">确认收货
                            </van-button>
                            <!-- <van-button type="success" size="mini" v-if="item.status != 5">已支付</van-button> -->

                            <van-button type="success" size="mini" v-if="item.status == 4"
                                color="linear-gradient( 135deg, #69FF97 10%, #00E4FF 100%)">已评价</van-button>
                            <van-button color="linear-gradient(to right, #ff6034, #ee0a24)" size="mini"
                                v-if="item.status == 3"
                                :to="{ path: '/user/order/comments', query: { orderid: item.id } }">待评价
                            </van-button>
                        </van-collapse-item>
                    </van-collapse>
                </div>

                <van-empty v-else image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
                    image-size="80" description="订单数据是空的">
                </van-empty>
            </van-tab>
        </van-tabs>


        <!-- TODO 支付 -->
        <van-dialog v-model:show="showKeyboard" title="请输入支付密码" theme="round-button" confim-button-text="再想想">

            <van-password-input :value="pwd" info="密码为6位数字" :error-info="errorInfo" :focused="showKeyboard" :length="6"
                @focus="showKeyboard = true" />

        </van-dialog>

        <van-number-keyboard v-model="pwd" :show="showKeyboard" @blur="showKeyboard = false" />

        <!-- TODO 确定收货组件 -->
        <van-popup v-model:show="showPop" round closeable close-icon="close" position="bottom"
            :style="{ height: 'auto' }">
            <template #default>
                <div class="popup">
                    <p class="title">确认收到货了吗</p>

                    <van-card class="p_tit" v-for="(item, index) in productInfo.order_product" :key="item.id"
                        :price="item.price" :desc="item.product.content_text" :title="item.product.name"
                        :thumb="item.product.cover_cdn" :num="item.nums" />
                    <van-cell>
                        <template #title>
                            <p style="text-align: center;">为了保证你的售后权益，请收到商品确认无误后再确认收货</p>
                        </template>
                    </van-cell>

                    <van-button class="sureim" round type="primary" block
                        color="linear-gradient(to right, #ff6034, #ee0a24)" @click="onSure(SureOrderid)">确定
                    </van-button>
                </div>
            </template>
        </van-popup>

        <!-- TODO 交易成功提示 -->
        <van-popup style="background: #f2f2f2;" v-model:show="showTips" round closeable close-icon="close"
            position="bottom" :style="{ height: '100%' }">
            <template #default>
                <div class="popup">
                    <p class="tip_title">
                        <van-icon name="checked" class="icon" />
                    <h2>交易成功</h2>
                    </p>

                    <div class="tip_flex">
                        <van-button class="tip_btn" type="primary" round size="small" @click="back">返回首页</van-button>
                        <van-button class="tip_btn" type="primary" round size="small"
                            color="linear-gradient(to right, #ff6034, #ee0a24)" @click="toComment">立即评价
                        </van-button>
                    </div>

                    <van-cell-group inset>
                        <van-cell class="vcell" title="温馨提示" size="large" label="评论完后晒单能返现哦~" center>
                            <template #icon>
                                <van-icon name="gem" color="#faa64b" size="40px" style="margin-right: 1.25rem;" />
                            </template>
                        </van-cell>
                    </van-cell-group>


                    <div class="likebox">
                        <ul class="proul">
                            <li v-for="(item, index) in LikeProducts" :key="item.id">
                                <router-link :to="{ path: '/product/base/detail', query: { id: item.id } }"><img
                                        :src="item.cover_cdn" />
                                </router-link>
                                <router-link :to="{ path: '/product/base/detail', query: { id: item.id } }">
                                    <p class="tit">
                                        {{ item.name }}
                                    </p>
                                </router-link>
                                <div class="price">
                                    <p>￥{{ item.price }}</p>
                                </div>
                            </li>

                        </ul>
                    </div>
                </div>
            </template>
        </van-popup>
    </div>
</template>

<script>
import Navbar from '../Navbar.vue'
export default {
    name: "Orders",
    data() {
        return {
            status: 0,
            titles: [],
            Orders: [],
            active: 0,
            activeName: 2,
            userid: this.$cookies.get('ShopUser').id,
            showKeyboard: false,
            showTips: false,
            errorInfo: '',
            pwd: '',
            orderid: '',
            toCommontOrderId: '',
            show: true,
            tags: [
                {
                    title: '全部',
                    name: 0
                },
                {
                    title: '已支付',
                    name: 1
                },
                {
                    title: '已发货',
                    name: 2
                },
                {
                    title: '已收货',
                    name: 3
                },
                {
                    title: '已评价',
                    name: 4
                },
                {
                    title: '待支付',
                    name: 5
                },
                {
                    title: '申请退货',
                    name: -2
                },
                {
                    title: '已退货',
                    name: -1
                },
            ],
            showPop: false,
            productInfo: [],
            SureOrderid: '',
            LikeProducts: []
        }
    },
    methods: {
        goBack() {
            this.$router.go(-1);
        },
        Aftersales() {
            this.$dialog.confirm({
                title: '提示',
                message: '暂无售后服务,敬请期待',
                theme: 'round-button',
            })
        },
        onClickTab(val) {
            this.Orders = null
            this.initOrders(val.name);
        },
        async initOrders(val) {
            let data = {
                userid: this.userid,
                status: val,
            }
            // console.log(data);
            let res = await this.$api.initOrders(data);
            // console.log(res);
            // 1 待发货
            // 2、待收货
            // 3、待评价
            // 4、已评价
            // 5、待付款       
            // -1、退货 
            // -2、退货中

            if (res.code === 1) {
                this.$toast.loading({
                    duration: 800,
                    loadingType: 'spinner',
                    onClose: () => {
                        this.show = true

                        this.tags.forEach((item, index) => {
                            if (val == item.name) {
                                this.active = index
                            }
                        });

                        this.Orders = res.data
                    }
                })
            } else {
                this.$toast.loading({
                    duration: 800,
                    loadingType: 'spinner',
                    onClose: () => {
                        this.show = false
                        this.Orders = null
                        // console.log(res.msg);
                    }
                })
            }
        },
        goToCash(orderid) {
            this.orderid = orderid
            this.show = true
            this.showKeyboard = true
        },
        showPopup(orderid) {
            this.Orders.forEach(element => {
                if (element.id == orderid) {
                    this.productInfo = element
                    this.SureOrderid = element.id
                }
            });
            this.showPop = true
        },
        back() {
            this.showTips = false
            this.initOrders(0)
        },
        // TODO 确认收货
        async onSure(orderid) {
            let res = await this.$api.receiving({ orderid });

            if (res.code === 1) {
                this.$toast.loading({
                    forbidClick: true,
                    duration: 500,
                    onClose: () => {
                        this.$toast.success({
                            message: res.msg,
                            duration: 1000,
                            onClose: () => {
                                this.showPop = false
                                this.showTips = true

                                this.toCommontOrderId = orderid
                                // TODO 确认收货后弹出
                                this.initOrders(0)
                                return false
                            }
                        })
                    }
                })
            } else {
                this.$toast.fail({
                    message: res.msg,
                    duration: 1000,
                    onClose: () => {
                        this.showPop = false
                    }
                })

                return false

            }
        },
        // TODO 删除订单功能
        deleteOrder(orderid) {
            this.$dialog.alert({
                title: '提示',
                message: '是否删除该订单',
                theme: 'round-button',
                showCancelButton: true,
                closeOnClickOverlay: true
            }).then(async () => {
                let res = await this.$api.delete({ orderid: orderid });

                if (res.code === 1) {
                    this.$toast.success({
                        message: res.msg,
                        duration: 1000,
                        onClose: () => {
                            this.showPop = false
                            this.initOrders(0)
                            return false
                        }
                    })
                } else {
                    this.$toast.fail({
                        message: res.msg,
                        duration: 1000,
                        onClose: () => {
                            this.showPop = false
                        }
                    })
                    return false
                }
            }).catch(() => {
                // on cancel
            });
        },
        async initLikeProduct() {
            let res = await this.$api.initProducts();
            if (res.code === 1) {
                this.LikeProducts = res.data.tuiProducts;
            } else {
                this.$notify({
                    type: "warning",
                    message: "获取失败",
                    onClose: () => {
                        return false;
                    },
                });
            }
        },
        toComment() {
            this.$router.push({ path: '/user/order/comments', query: { orderid: this.toCommontOrderId } })
        }
    },
    watch: {
        pwd(newVal, oldVal) {
            let data = {
                orderid: this.orderid,
                userid: this.userid,
            }

            if (newVal.length === 4) {
                if (newVal === '1234') {
                    this.$toast.loading({
                        message: '支付中...',
                        duration: 1500,
                        onClose: async () => {
                            this.show = false
                            this.showKeyboard = false
                            this.pwd = ''

                            let res = await this.$api.cash(data);

                            console.log(res);
                            // return false
                            if (res.code === 1) {
                                this.$toast.success({
                                    duration: 1500,
                                    message: res.msg,
                                    onClose: () => {
                                        this.$router.push({ path: res.url, query: { orderid: res.data } });
                                    }
                                })
                            } else {
                                this.$notify({
                                    type: 'danger',
                                    message: res.msg,
                                    duration: 1500,
                                })
                            }
                        }
                    })
                } else {
                    this.$toast.fail({
                        message: '密码错误',
                        duration: 500,
                        onClose: () => {
                            this.show = false
                            this.showKeyboard = false
                            this.pwd = ''
                        }
                    })
                }
            }
        }
    },
    created() {
        let status = this.$route.query.status ? this.$route.query.status : this.status;
        console.log(status);

        this.initOrders(status);
        this.initLikeProduct()
    },
    components: {
        Navbar
    }
}
</script>

<style scoped>
.title {
    text-align: center;
    font-size: 1.1rem;
    font-weight: 700;
    padding: 5px;
    margin-top: 10px;
}

.popup .sureim {
    max-width: 90%;
    margin: 0 auto;
    margin-top: 10px;

}

:deep(.van-card__price) {
    width: 100%;
}

:deep(.van-number-keyboard) {
    z-index: 9999;
}

:deep(.van-card) {
    margin-top: 0;
}

.proul li {
    border-radius: 10px;
}

.tip_title {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1rem;
    color: #000;
    margin-top: 2.5rem;
}

.tip_title .icon {
    color: orangered;
    font-size: 1.25rem;
    margin: 15px 0;
    margin-right: .625rem;
}

.tip_flex {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
}

.tip_btn {
    margin: 0 .3125rem;
}

.flex {
    display: flex;
    justify-content: space-between;

}

.items_t {
    border-top-right-radius: 20px;
    border-top-left-radius: 20px;
}

.items_b {
    border-bottom-right-radius: 20px;
    border-bottom-left-radius: 20px;
}

:deep(.van-collapse-item__wrapper) {
    border-bottom-right-radius: 20px;
    border-bottom-left-radius: 20px;
}

.items {
    margin: 10px;
    border-radius: 20px;
    box-shadow: 0 8px 12px #ebedf0;
}

:deep(.van-card) {
    background: #fff;
}
</style>